# \zennotac-backend\app\routes\excel.py
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from app.services.exceling_pdf import generate_excel_from_text, generate_excel_from_table
from app.utils.filename_helper import sanitize_filename
from app.config.base_setting import OCR_OUTPUT_FOLDER
from app.config.base_setting import backend_logger
import os

router = APIRouter()

class FilenamePayload(BaseModel):
    filename: str

@router.post("/excel/text")
async def excel_text(payload: FilenamePayload):
    """
    Generate Excel from structured OCR text.
    Returns task ID for progress tracking.
    """
    try:
        filename = sanitize_filename(payload.filename)
        input_path = os.path.join(OCR_OUTPUT_FOLDER, filename)

        if not os.path.exists(input_path):
            backend_logger.warning(f"[EXCEL TEXT] File not found: {filename}")
            raise HTTPException(status_code=404, detail="Ocred file not found.")

        result = generate_excel_from_text(input_path)

        return {
            "message": "Excel file generated from text successfully",
            **result  # includes task_id, output_file, source_file, processing_time, etc.
        }

    except Exception as e:
        backend_logger.exception(f"[EXCEL TEXT ERROR] {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/excel/table")
async def excel_table(payload: FilenamePayload):
    """
    Generate Excel from structured OCR table content.
    Returns task ID for progress tracking.
    """
    try:
        filename = sanitize_filename(payload.filename)
        input_path = os.path.join(OCR_OUTPUT_FOLDER, filename)

        if not os.path.exists(input_path):
            backend_logger.warning(f"[EXCEL TABLE] File not found: {filename}")
            raise HTTPException(status_code=404, detail="Ocred file not found.")

        result = generate_excel_from_table(input_path)

        return {
            "message": "Excel file generated from table successfully",
            **result
        }

    except Exception as e:
        backend_logger.exception(f"[EXCEL TABLE ERROR] {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

# @router.post("/excel/text")
# async def excel_text(payload: FilenamePayload):
#     """
#     Generate Excel from structured OCR text.
#     """
#     try:
#         filename = sanitize_filename(payload.filename)
#         input_path = os.path.join(OCR_OUTPUT_FOLDER, filename)

#         if not os.path.exists(input_path):
#             logger.warning(f"[EXCEL TEXT] File not found: {filename}")
#             raise HTTPException(status_code=404, detail="Ocred file not found.")

#         output_path = generate_excel_from_text(input_path)

#         return {
#             "message": "Excel file generated from text successfully",
#             "output_file": os.path.basename(output_path)
#         }

#     except Exception as e:
#         logger.exception(f"[EXCEL TEXT ERROR] {str(e)}")
#         raise HTTPException(status_code=500, detail=str(e))


# @router.post("/excel/table")
# async def excel_table(payload: FilenamePayload):
#     """
#     Generate Excel from structured OCR table content.
#     """
#     try:
#         filename = sanitize_filename(payload.filename)
#         input_path = os.path.join(OCR_OUTPUT_FOLDER, filename)

#         if not os.path.exists(input_path):
#             logger.warning(f"[EXCEL TABLE] File not found: {filename}")
#             raise HTTPException(status_code=404, detail="Ocred file not found.")

#         output_path = generate_excel_from_table(input_path)

#         return {
#             "message": "Excel file generated from table successfully",
#             "output_file": os.path.basename(output_path)
#         }

#     except Exception as e:
#         logger.exception(f"[EXCEL TABLE ERROR] {str(e)}")
#         raise HTTPException(status_code=500, detail=str(e))
